﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Collections;

namespace Authority.Core
{
    public enum PopedomTypes : int
    {
        Read = 1,
        Write = 2,
        Modify = 4,
        Delete = 8,
        Create = 16
    }

    public class User
    {
        public PopedomTypes Permissions { get; set; }
        public string userName { get; set; }
    }

    //为枚举扩展几个方法
    public static class PermissionAction
    {
        public static bool Has<T>(this System.Enum type, T value)
        {
            try
            {
                return ((int)(object)type & (int)(object)value) == (int)(object)value;
            }
            catch
            {
                return false;
            }
        }

        public static bool Is<T>(this System.Enum type, T value)
        {
            try
            {
                return (int)(object)type == (int)(object)value;
            }
            catch
            {
                return false;
            }
        }

        public static T Add<T>(this System.Enum type, T value)
        {
            try
            {
                return (T)(object)(((int)(object)type | (int)(object)value));
            }
            catch (Exception ex)
            {
                throw new ArgumentException(
                    string.Format(
                        "不能添加类型 '{0}'",
                        typeof(T).Name
                        ), ex);
            }
        }

        public static T Remove<T>(this System.Enum type, T value)
        {
            try
            {
                return (T)(object)(((int)(object)type & ~(int)(object)value));
            }
            catch (Exception ex)
            {
                throw new ArgumentException(
                    string.Format(
                        "不能移除类型 '{0}'",
                        typeof(T).Name
                        ), ex);
            }
        }

        public static Hashtable GetPermission<T>(this System.Enum type, T value)
        {
            Hashtable ht = new Hashtable();
            String[] permissionName = Enum.GetNames(typeof(PopedomTypes));
            int i = 0;
            foreach (int permissionValue in Enum.GetValues(typeof(PopedomTypes)))
            {
                if (((int)(object)value & permissionValue) == permissionValue)
                {
                    ht.Add(permissionName[i], "True");
                }
                else
                {
                    ht.Add(permissionName[i], "False");
                }
                i++;
            }
            return ht;
        }
    }
}